package org.truenewx.tnxjee.service.exception.model;

import org.truenewx.tnxjee.core.Strings;
import org.truenewx.tnxjee.service.exception.BusinessException;
import org.truenewx.tnxjee.service.exception.FormatException;
import org.truenewx.tnxjee.service.exception.SingleException;

/**
 * 来源于异常的错误
 *
 * @author jianglei
 */
public class ExceptionError extends CodedError {

    private String type;
    private String field;
    private String detail;

    public ExceptionError() {
    }

    public ExceptionError(SingleException se, String message) {
        super(se.getCode(), message);
        this.type = se.getClass().getName();
        this.field = se.getProperty();
    }

    public ExceptionError(String code, String message, RuntimeException re) {
        super(code, message);
        this.type = re.getClass().getName();
        this.detail = re.getClass().getSimpleName() + Strings.COLON + Strings.SPACE + re.getMessage();
    }

    public String getType() {
        return this.type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getField() {
        return this.field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getDetail() {
        return this.detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public SingleException toException() {
        if (this.type != null) {
            try {
                Class<?> clazz = Class.forName(this.type);
                if (clazz == FormatException.class) {
                    return new FormatException(this);
                }
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        return new BusinessException(this);
    }

}
